<!-- 结转页面 -->
<template>
  <div>
    <el-card v-loading="loadingDiv">
      <el-form
        :inline="true"
        size="mini"
        :model="searchCriteria"
        class="padding-top-sm flex justify-between"
      >
        <el-form-item prop="instockDate" :label="carryOverTimeLabel">
          <el-date-picker
            type="daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="searchCriteria.instockDate"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="pickerOptions"
            style="width: 220px"
          ></el-date-picker>
          <!-- <span class="margin-lr-sm">-</span> -->
        </el-form-item>
        <el-form-item label="使用签收时间结转" prop="useSignTimeCarryOver">
          <el-switch v-model="searchCriteria.useSignTimeCarryOver"></el-switch>
        </el-form-item>
        <el-form-item prop="costDate" label="费用时间">
          <el-date-picker
            type="daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="searchCriteria.costDate"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 220px"
          ></el-date-picker>
        </el-form-item>

        <el-radio-group v-model="searchCriteria.receiveOrPay">
          <el-radio :label="0">应收</el-radio>
          <el-radio :label="1">应付</el-radio>
        </el-radio-group>
        <el-form-item prop="accountMonth" label="所属月份">
          <el-date-picker
            value-format="yyyy-MM"
            type="month"
            style="width: 200px"
            placeholder="请输入选择月份"
            v-model="searchCriteria.accountMonth"
          ></el-date-picker>
        </el-form-item>
        <el-button size="mini" type="primary" @click="receivePayCarryOver()"
          >结转
        </el-button>
      </el-form>
      <el-divider></el-divider>
      <div>
        <p class="margin-bottom-sm">1.支持使用签收时间结转(海外仓依旧是处理时间)，系统设定是2022-01-01后入库的单，阿米巴结算日期调整成签收日期，建议2022-01-01之前入库的使用入库时间结转，之后的使用签收时间结转</p>
        <p class="margin-bottom-sm">2.入库时间、费用时间同时填写，取并集</p>
        <p class="margin-bottom-sm">
          3.如果所属月份已经期末结帐,本月不允许再结转
        </p>
        <p class="margin-bottom-sm">4.入库时间、费用时间最后日期只能是昨日</p>
        <p class="margin-bottom-sm">
          5.所属月份未期末结帐,可以多次结转、反结转
        </p>
        <p class="margin-bottom-sm">6.海外仓：入库时间调整为处理时间</p>
        <p class="margin-bottom-sm">
          7.应收已结转时间段：{{ timeData.financeVoucherCarryOverReceiveRange }}
        </p>
        <p class="margin-bottom-sm">
          8.应付已结转时间段：{{ timeData.financeVoucherCarryOverPayRange }}
        </p>
        <p class="margin-bottom-sm">
          9.结转所属月份：{{ timeData.financeVoucherCarryOverMonths }}
        </p>
      </div>
    </el-card>

    <el-row v-loading="loadingVerifyDiv">
      <el-col :span="14">
        <el-card class="box-card" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span style="font-size: 14px;font-weight: bold;"
              >校验并修复结转应收、应付对应的阿米巴费用(结转后,结账前使用此功能)</span
            >
          </div>
          <el-row>
            <el-col :span="10">
              <div>
                <el-form
                  size="mini"
                  :inline="true"
                  :model="carryOverVerifyForm"
                >
                  <el-form-item label="校验结转月份">
                    <el-date-picker
                      value-format="yyyy-MM"
                      type="month"
                      style="width: 200px"
                      placeholder="请输入结转月份"
                      v-model="carryOverVerifyForm.accountMonth"
                    ></el-date-picker>
                  </el-form-item>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="verifyAmoebaByCarryOverMonth"
                    >校验</el-button
                  >
                </el-form>
              </div>
            </el-col>
            <el-col :span="14">
              <div>
                <template>
                  <el-table
                    :data="financeCarryOverVerifyLogs"
                    style="width: 100%"
                  >
                    <el-table-column prop="cdate" label="校验时间" width="180">
                    </el-table-column>
                    <el-table-column prop="month" label="结转月份" width="130">
                    </el-table-column>
                    <el-table-column prop="result" label="校验结果">
                    </el-table-column>
                  </el-table>
                </template>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="9" :offset="1">
        <el-card class="box-card" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span style="font-size: 14px;font-weight: bold;"
              >校验合单分配费用(结果会导出成EXCEL)</span
            >
          </div>
          <el-form size="mini" :inline="true" :model="mergeFeeVerifyForm">
            <el-form-item label="校验月份">
              <el-date-picker
                value-format="yyyy-MM"
                type="month"
                style="width: 200px"
                placeholder="请输入月份"
                v-model="mergeFeeVerifyForm.accountMonth"
              ></el-date-picker>
            </el-form-item>
            <el-button
              size="mini"
              type="primary"
              @click="verifyWaybillMergeAllocation"
              >校验</el-button
            >
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <div class="padding color margin-top">
      结转记录
      <el-button
        style="margin-left: 20px"
        type="primary"
        size="mini"
        plain
        round
        @click="massDownLoadCarryOverData"
        >批量导出对应数据(无B费用)
      </el-button>
    </div>
    <el-card v-loading="tableLoading">
      <el-table
        :data="tableDataListAll"
        class="text-sm"
        @selection-change="handleSelectionChange"
        :cell-class-name="cellClass"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="序号" width="50"></el-table-column>
        <el-table-column label="操作日志">
          <template slot-scope="scope">
            <div v-html="scope.row.rowHtml"></div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注"></el-table-column> -->
        <el-table-column label="操作" width="500">
          <template slot-scope="scope" v-if="scope.row.status == 1">
            <el-button
              :disabled="disabled"
              type="primary"
              size="mini"
              plain
              v-loading.fullscreen.lock="fullscreenLoading"
              @click="downLoadCarryOverDatas(scope.row.id)"
              >实时导出对应数据(无B费用)
            </el-button>
            <el-button
              :disabled="disabled"
              type="primary"
              size="mini"
              plain
              v-loading.fullscreen.lock="fullscreenLoading"
              @click="downLoadCarryOverDatas2(scope.row.fileName)"
              v-if="scope.row.fileName !== null || scope.row.fileName !== ''"
              >导出结转记录
            </el-button>
            <el-button
              type="warning"
              size="mini"
              plain
              @click="showReceivePayCarryOverVoucher(scope.row.id)"
              >查看凭证
            </el-button>
            <el-button
              :disabled="disabled"
              :loading="scope.row.btnLoading"
              type="success"
              size="mini"
              plain
              @click="reverseReceivePayCarryOver(scope.row.id, scope)"
            >
              反结转
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="查看对应凭证"
        :visible.sync="dialogTableVisible"
        top="10vh"
      >
        <div style="height:400px;" class="scrollbar">
          <el-table
            v-loading="loading"
            element-loading-text="拼命加载中"
            height="400"
            element-loading-spinner="el-icon-loading"
            :data="tableDataDetail"
            class="text-sm"
          >
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column
              v-for="(item, index) in tableColumns"
              :key="index"
              :prop="item.prop"
              :label="item.label"
            >
              <!--userMap 的特殊处理-->
              <template slot-scope="scope">
                <template v-if="item.prop === 'cuser'">
                  {{ userMap[scope.row.cuser] }}
                </template>
                <template v-else>
                  {{ scope.row[item.prop] }}
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";

export default {
  data() {
    let that = this;
    return {
      data: "",
      duration: [],
      ids: [],
      mqCount: "",
      timer: "",
      disabled: false,
      carryOverTimeLabel: '入库时间',
      //查询数据
      searchCriteria: {
        instockDate: "",
        accountMonth: "",
        costDate: "",
        receiveOrPay: "",
        useSignTimeCarryOver: false
      },
      carryOverVerifyForm: {
        accountMonth: ""
      },
      mergeFeeVerifyForm: {
        accountMonth: ""
      },
      financeCarryOverVerifyLogs: [],
      //loading
      fullscreenLoading: false,
      loadingVerifyDiv: false,
      tableDataListAll: [], // 最外面 全部 表格数据
      tableDataDetail: [], //表格详细数据
      userMap: {}, //用户map
      timeData: {},
      // 表格表头
      tableColumns: [
        { prop: "accountDate", label: "期间" },
        { prop: "voucherNo", label: "凭证号" },
        { prop: "accountDate", label: "凭证日期" },
        { prop: "totalDebitMoney", label: "借方金额" },
        { prop: "totalCreditorMoney", label: "贷方金额" },
        { prop: "cuser", label: "制单人" },
        { prop: "cdate", label: "创建时间" }
      ],
      //loading框加载中
      loading: true,
      loadingDiv: false,
      tableLoading: false,
      //详情显示 不显示
      dialogTableVisible: false,
      pickerOptions: {
        disabledDate(time) {
          let currentTime = that.duration[0];
          let threeMonths = 60 * 60 * 1000 * 24 * 365;
          if (currentTime) {
            return (
              time.getTime() > currentTime.getTime() + threeMonths ||
              time.getTime() < currentTime.getTime() - threeMonths
            );
          }
        },
        onPick({ minDate, maxDate }) {
          // 当第一时间选中才设置禁用
          if (minDate && !maxDate) {
            that.duration[0] = minDate;
          }
          if (maxDate) {
            that.duration[1] = maxDate;
          }
        }
      }
    };
  },
  // watch:{
  //   'useSignTimeCarryOver'(val){
  //     console.log(val)
  //   }
  // },
  watch: {
    'searchCriteria.useSignTimeCarryOver': {
      handler(nVal) {
        console.log(nVal)
        if(nVal){
          this.carryOverTimeLabel = '签收时间';
        }else{
          this.carryOverTimeLabel = '入库时间';
        }
      }
    }
  },
  methods: {
    cellClass(row) {
      if (row.row.status !== 1) {
        return "hideCheckBoxCell";
      }
    },
    handleSelectionChange(arr) {
      let temIds = [];
      arr.map(val => {
        temIds.push(val["id"]);
      });
      this.ids = temIds;
      console.log(temIds);
    },
    getMqCount() {
      let queues = [
        "YGBOOST-DATABASE-SYNC20",
        "YGBOOST-DATABASE-SYNC21",
        "YGBOOST-DATABASE-SYNC22",
        "YGBOOST-DATABASE-SYNC23",
        "YGBOOST-DATABASE-SYNC24",
        "YGBOOST-DATABASE-SYNC25",
        "YGBOOST-DATABASE-SYNC26",
        "YGBOOST-DATABASE-SYNC27",
        "YGBOOST-DATABASE-SYNC28",
        "YGBOOST-DATABASE-SYNC29"
      ];
      axios
        .get(
          constant.API_SERVER +
            "/open/getMqCount?queues=" +
            JSON.stringify(queues)
        )
        .then(
          response => {
            if (200 == response.status) {
              this.mqCount = response.data;
              // console.log("this.mqCount: ", this.mqCount);
              if (this.mqCount > 0) {
                this.disabled = true;
              }
              if (0 == this.mqCount) {
                clearInterval(this.timer);
                this.disabled = false;
              }
            }
          },
          response => {}
        );
    },
    async init() {
      this.tableLoading = true;
      const financeCarryOverVerifyLogs = await ajax(
        "queryFinanceCarryOverVerifyLogs",
        {}
      );
      this.financeCarryOverVerifyLogs = financeCarryOverVerifyLogs;
      const { code, data, data2, data3, message } = await ajax("logs", {});
      if (code !== 200) {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      }
      //console.log("data",data);
      if (data && data.length > 0) {
        data.forEach(element => {
          let rowHtml = "";
          if (element.cdate !== null) {
            rowHtml = rowHtml + element.cdate;
          }
          if (element.cuser !== null && data2) {
            rowHtml = rowHtml + data2[element.cuser];
          }
          if (element.remark !== null) {
            rowHtml = rowHtml + element.remark;
          }
          if (element.accountMonth !== null) {
            rowHtml = rowHtml + element.accountMonth;
          }
          //console.log("rowHtml",rowHtml);
          element.rowHtml = rowHtml;
        });
      }
      this.tableDataListAll = data;
      // console.log("tableDataListAll",this.tableDataListAll);
      // 添加btnLoading字段
      this.tableDataListAll = this.tableDataListAll.map(item => {
        this.$set(item, "btnLoading", false);
        return item;
      });
      this.userMap = data2;
      this.timeData = data3;
      this.tableLoading = false;
    },
    async verifyWaybillMergeAllocation() {
      if (!this.mergeFeeVerifyForm.accountMonth) {
        this.$message.error("结转月份必填");
        return;
      }
      this.loadingVerifyDiv = true;
      const { code, data, message } = await ajax(
        "verifyWaybillMergeAllocation",
        this.mergeFeeVerifyForm
      );
      if (code === 200) {
        var path = (path = constant.FILE_SERVER + message);
        location.href =
          constant.API_SERVER +
          "/open/downloadFileByHttp?fileName=&path=" +
          path;
      } else {
        this.$message.error(message);
      }
      this.loadingVerifyDiv = false;
    },
    async verifyAmoebaByCarryOverMonth() {
      if (!this.carryOverVerifyForm.accountMonth) {
        this.$message.error("结转月份必填");
        return;
      }
      this.loadingVerifyDiv = true;
      const { code, data, message } = await ajax(
        "verifyAmoebaByCarryOverMonth",
        this.carryOverVerifyForm
      );
      if (code === 200) {
        this.$message.success("操作成功");
      } else {
        this.$message.error(message);
      }
      this.loadingVerifyDiv = false;
    },
    //点击转结 按钮 的操作
    async receivePayCarryOver() {
      if (!this.searchCriteria.instockDate) {
        this.$message.error("入库时间必填");
        return;
      }
      this.loadingDiv = true;
      this.searchCriteria.startInstockDate = this.searchCriteria.instockDate[0];
      this.searchCriteria.endInstockDate = this.searchCriteria.instockDate[1];
      // 不是空的就去 组装数据
      if (this.searchCriteria.costDate) {
        this.searchCriteria.startCostDate = this.searchCriteria.costDate[0];
        this.searchCriteria.endCostDate = this.searchCriteria.costDate[1];
      }
      // 入库时间不能超过3个月 2021-12-07

      let attrs = {};
      attrs["headers"] = {
        "YG-UNIQUE-KEY": "receivePayCarryOver" + new Date().getTime()
      };
      const { code, data, message } = await ajax(
        "receivePayCarryOver",
        this.searchCriteria,
        attrs
      );
      if (code === 200) {
        this.$message.success("结转成功");
        setTimeout(() => {
          location.reload();
        }, 2000);
      } else {
        this.$message.error(message);
      }
      this.loadingDiv = false;
    },
    //导出对应数据(无B费用)
    async downLoadCarryOverDatas(id) {
      //开启遮罩层
      this.fullscreenLoading = true;
      const { code, data, data2, message } = await ajax(
        "downLoadCarryOverDatas",
        {
          id: id
        }
      );
      if (code !== 200) {
        this.fullscreenLoading = false;
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      } else {
        this.fullscreenLoading = false;
        var path = constant.FILE_SERVER + data2;
        location.href =
          constant.API_SERVER +
          "/open/downloadFileByHttp?fileName=" +
          data +
          "&path=" +
          path +
          data;
      }
    },
    //
    async downLoadCarryOverDatas2(fileName) {
      if (fileName === null || fileName === undefined || fileName === "") {
        this.$message.error("尚未生成记录");
        return;
      }
      var path = constant.FILE_SERVER + fileName;
      location.href =
        constant.API_SERVER + "/open/downloadFileByHttp?fileName=&path=" + path;
    },

    async massDownLoadCarryOverData() {
      if (this.ids.length == 0) {
        this.$message.warning("至少选中一条");
        return;
      }
      //开启遮盖层
      this.fullscreenLoading = true;
      const { code, data, data2, message } = await ajax(
        "massDownLoadCarryOverData",
        {
          ids: this.ids
        }
      );
      if (code !== 200) {
        this.fullscreenLoading = false;
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      } else {
        this.fullscreenLoading = false;
        let path = constant.FILE_SERVER + data2;
        location.href =
          constant.API_SERVER +
          "/open/downloadFileByHttp?fileName=" +
          data +
          "&path=" +
          path +
          data;
      }
    },
    //查看凭证
    async showReceivePayCarryOverVoucher(id) {
      this.tableDataDetail = [];
      this.dialogTableVisible = true;
      const {
        code,
        data,
        message
      } = await ajax("showReceivePayCarryOverVoucher", { id: id });
      if (code !== 200) {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      } else {
        this.tableDataDetail = data;
        this.loading = false;
      }
    },
    //反结转
    async reverseReceivePayCarryOver(id, scope) {
      // 改变当前行的btnLoading状态-开启
      this.$set(scope.row, "btnLoading", true);
      const { code, data, message } = await ajax("reverseReceivePayCarryOver", {
        id: id
      });
      if (code !== 200) {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      } else if (code == 200) {
        this.$message.success("反结转成功");
        setTimeout(() => {
          location.reload();
        }, 2000);
      } else {
        this.$message.error("程序异常");
      }
      // 改变当前行的btnLoading状态-关闭
      this.$set(scope.row, "btnLoading", false);
    }
  },
  mounted() {
    this.init();
    this.getMqCount();
    this.timer = setInterval(() => {
      this.getMqCount();
    }, 3000);
  },
  beforeDestory() {
    clearInterval(this.timer);
  }
};
</script>

<style>
.color {
  background-color: #dff0d8;
  color: #3c763d;
  background-image: linear-gradient(to bottom, #dff0d8 0, #d0e9c6 100%);
}

.hideCheckBoxCell .el-checkbox__input {
  display: none;
}
</style>
